import { AsyncStorage } from 'react-native';
import { kAuthorization } from "../constant";
import Request from "../utils/Request";
const STORAGE_KEY = "STORAGE_KEY_group";
export default {
    namespace: 'group',
    state: {
        loading: false,
        postList: [],
        comments: [],
        praise: []
    },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *saveToStorage({ payload }, { call }) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        *restoreFromStorage({ payload }, { call, put, select }) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: Object.assign({}, JSON.parse(data))
            });
        },
        *clear({ payload }, { put }) {
        },
        *fetchGroupPosts({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            let groupId = payload.groupId;
            delete payload.groupId;
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const res = yield call(Request.get, Request.getApi().groupPosts + `/${groupId}`, payload);
            if (res) {
                const postList = res;
                yield put({
                    type: 'save',
                    payload: {
                        postList
                    }
                });
            }
        }
    },
    subscriptions: {
        setup({ dispatch }) {
        }
    },
};
